import React, { PureComponent } from 'react';
import { PrimaryC, DATA_ENTRY, ContentPackage, AdvancedSearch, NoQueryC, TableC } from '@/src/components';
import ModalInst from './Modal';
import { connect } from 'dva';
import { fixedNum, getProductName } from '@/src/utils/utils';
import style from './index.less';

@connect(({ creditSettingM, productAGroupM, globalM, userM: user, loading }) => ({
  creditSettingM,
  productAGroupM,
  globalM,
  user,
  loading: loading.effects['creditSettingM/getCreditList'],
}))
export default class CreditSetting extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      visible: false, // 控制模态框
      columns: [], // table 字段
      dataSource: [], // table数据
      pageInfo: {}, // 分页信息
      currentPage: 1, // 当前页
      numInPage: 20, // 每页数量
      sortedInfo: null, // 排序对象
      orderByField: '', // 按某列排序
      order: '', // 升序降序
      search: {},
      detailData: {}, // 授信详情数据
      productList: [], // 产品组数据
      isZiGuan: false, // 是否是资管环境
    };
  }

  componentDidMount() {
    // 获取产品组数据 用处理表格的产品组 名称
    this.props.dispatch({
      type: 'productAGroupM/getProductGroups',
      payload: {},
      callback: (e) => {
        this.setState({
          productList: e.groupsList, // 列表下拉数据
          columns: this.state.columns ? [...this.state.columns] : [],
        });
      },
    });
    // 交易对手短名下拉列表
    this.props.dispatch({
      type: 'creditSettingM/getShortName',
      payload: {},
    });
  }

  // 点击重置按钮
  onClear = () => {
    this.setState({
      search: {},
      currentPage: 1,
      numInPage: 20,
    });
  };

  // 点击查询按钮刷新数据
  getTableData = (type) => {
    const { dispatch } = this.props;
    const { order, orderByField, numInPage, currentPage, search } = this.state;
    const sortedInfo = this.state.sortedInfo ? this.state.sortedInfo : {};

    if (Object.keys(sortedInfo).length && sortedInfo.columnKey != 'shortName' && sortedInfo.columnKey != 'isParentOccupated') return; // 阻止非排序列调用
    const params = {};
    params.numInPage = numInPage;
    if (type != 'pageChange') {
      // 点击查询按钮或者删除某一条重新查询列表 重置页码
      this.setState({
        currentPage: 1,
      });
      params.currentPage = 1;
    } else {
      // 点击页码切换时候调用
      params.currentPage = currentPage;
    }
    // 列表数据
    dispatch({
      type: 'creditSettingM/getCreditList',
      payload: {
        ...params,
        ...search,
        order,
        orderByField,
      },
      callback: (data) => {
        this.setState({
          columns: data.columns,
          dataSource: data.dataSource,
          pageInfo: data.pageInfo,
        });
      },
    });
  };

  // 分页切换
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    let newOrder = '';
    sorter.order == 'descend' ? (newOrder = 'DESC') : sorter.order == 'ascend' ? (newOrder = 'ASC') : (newOrder = '');

    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
        sortedInfo: sorter,
        order: newOrder,
        orderByField: sorter.columnKey,
      },
      () => {
        this.getTableData('pageChange');
      },
    );
  };

  // 控制模态框显示隐藏
  setVisible = (e) => {
    this.setState({
      visible: e,
    });
  };

  // 点击新增 编辑 查看展示模态框
  showModal = (id, type) => {
    this.setState({
      detailData: {},
    });
    if (type != 'create') {
      this.props.dispatch({
        // 查询详情数据
        type: 'creditSettingM/getCreditDetail',
        payload: {
          id,
        },
        callback: (data) => {
          this.setState({
            detailData: data || {},
            visible: true,
          });
        },
      });
    } else {
      this.setState({
        visible: true,
      });
    }
    this.setState({
      type,
      title: type == 'create' ? '授信设置' : type == 'query' ? '授信查看' : '授信编辑',
    });
  };

  // 删除
  onDeleteFrom = (item) => {
    const { dispatch } = this.props;
    const that = this;
    dispatch({
      type: 'creditSettingM/deleteCredit',
      payload: {
        id: item.id,
      },
      callback: (msg) => {
        if (msg) {
          that.getTableData();
        }
      },
    });
  };

  // 字典转换文字显示
  showValue = (text, arr) => {
    if (!text) return '';
    let newData = '';
    arr.map((item) => {
      if (item.code == text) {
        newData = item.value;
      }
    });
    return newData;
  };

  expandedRowRender = (record) => {
    if (record.child && record.child.length && !record.child[0].key) {
      record.child.map((item, key) => {
        item.key = key;
      });
    }
    if (record.columns) {
      record.columns.map((item) => {
        item.dataIndex = item.key;
        if (item.key == 'remainMaturity') {
          item.width = '22%';
        }
        if (item.key == 'creditLine') {
          item.render = (text) => {
            // 未在有效期内 授信额度置灰 0是 1否
            return <span className={record.isEffective == '0' ? '' : style.creditLineDisable}>{fixedNum(text, 2)}</span>;
          };
        }
      });
    }

    return (
      <div className={style.expandTable}>
        <TableC columns={record.columns || []} dataSource={record.child || []} rowKey='key' hidePage={true} />
      </div>
    );
  };

  // 渲染表格
  renderTable = () => {
    const {
      globalM: {
        dataDictionary: { COUNTERPARTY_CurrencyType = [], COUNTERPARTY_MEASUREMENT_METHOD = [], COUNTERPARTY_BUSSINESS_TYPE = [], COUNTERPARTY_AVAILABLE_STATUS_DICT = [] },
      },
    } = this.props;

    const { columns, dataSource, pageInfo } = this.state;
    const { loading } = this.props;
    let { sortedInfo } = this.state;
    sortedInfo = sortedInfo || {};
    columns.map((item, key) => {
      item.dataIndex = item.key;
      if (item.key == 'shortName' || item.key == 'isParentOccupated') {
        item.sorter = true;
        item.sortOrder = sortedInfo.columnKey === item.key && sortedInfo.order;
      }
      if (item.key == 'portfolioName') {
        item.render = (text, record) => {
          // 找出产品组名称 原因是在资管，交易对手一个数据库，基础信息（包含用户信息、产品、组合、产品组等）一个库，两个库还不一样，所以数据没有共享
          return getProductName(record.portfolioId, this.state.productList) || '--';
        };
      }
      if (item.key == 'isParentOccupated') {
        item.render = (text, record) => {
          return text != null ? (text == 0 ? '是' : '否') : text || '--';
        };
      }
      if (item.key == 'businessType') {
        item.render = (text, record) => {
          if (text != null) {
            const arr = text.map((code) => {
              return this.showValue(code, COUNTERPARTY_BUSSINESS_TYPE);
            });
            return arr.join(',');
          }
          return text || '--';
        };
      }
      if (item.key == 'measurementMethod') {
        item.render = (text, record) => {
          if (text != null) {
            return this.showValue(text, COUNTERPARTY_MEASUREMENT_METHOD);
          }
          return text || '--';
        };
      }
      if (item.key == 'currencyType') {
        item.render = (text, record) => {
          if (text != null) {
            return this.showValue(text, COUNTERPARTY_CurrencyType);
          }
          return text || '--';
        };
      }
      if (item.key == 'status') {
        item.render = (text, record) => {
          return text !== null ? this.showValue(text, COUNTERPARTY_AVAILABLE_STATUS_DICT) : '--';
        };
      }
    });
    // 因为columns来自props，会不停的渲染添加操作列，在此做一下判断
    if (columns.length && columns[columns.length - 1].title != '操作') {
      columns.push({
        key: 'operation',
        dataIndex: 'operation',
        title: '操作',
        width: 137,
        type: 'operate',
        operates: [
          {
            title: '查看',
            onClick: (record, index) => this.showModal(record.id, 'query'),
          },
          {
            title: '修改',
            onClick: (record, index) => this.showModal(record.id, 'edit'),
            rules: {
              disabled: { relation: 'and', items: [{ key: 'status', value: ['1'], relation: ['!='] }] },
            },
          },
          {
            title: '删除',
            onClick: (record, index) => this.onDeleteFrom(record),
            rules: {
              disabled: { relation: 'and', items: [{ key: 'status', value: ['1'], relation: ['!='] }] },
            },
          },
        ],
      });
    }

    return (
      <div>
        {columns.length ? (
          <TableC
            columns={columns}
            dataSource={dataSource || []}
            onChange={this.handleTableChange}
            current={this.state.currentPage}
            pageSize={this.state.numInPage}
            selfScrollY={true}
            loading={loading}
            expandedRowRender={this.expandedRowRender}
            defaultExpandAllRows={false}
            total={pageInfo.total || 0}
            rowKey='id'
          />
        ) : (
          <div>
            <NoQueryC />
          </div>
        )}
      </div>
    );
  };

  render() {
    const {
      globalM: {
        dataDictionary: { COUNTERPARTY_AVAILABLE_STATUS_DICT = [] },
      },
    } = this.props;
    const availableList = COUNTERPARTY_AVAILABLE_STATUS_DICT.map((item) => {
      return {
        value: item.code,
        title: item.value,
      };
    });
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'portfolioId',
          type: DATA_ENTRY.PRODUCTGROUP,
        },
        {
          dataIndex: 'shortName',
          title: '交易对手短名',
          type: DATA_ENTRY.INPUT,
        },
        {
          dataIndex: 'longName',
          title: '交易对手长名',
          type: DATA_ENTRY.INPUT,
        },
        {
          dataIndex: 'status',
          title: '可用状态',
          type: DATA_ENTRY.SELECT,
          isMultiple: true,
          dataSource: this.state.isZiGuan ? availableList.filter((item, key) => key == 0) : availableList,
        },
      ],
      onQuery: (e) => {
        this.setState(
          {
            search: { ...e },
          },
          () => {
            this.getTableData();
          },
        );
      },
      onClear: () => {
        this.onClear();
      },
    };
    const { type, visible, title, detailData } = this.state;
    return (
      <ContentPackage
        title='授信设置'
        contentHtml={
          <div>
            <div className={style.creditSetting}>
              <AdvancedSearch {...searchProps} />
              <div style={{ marginTop: '13px' }}>
                <PrimaryC
                  onClick={() => {
                    this.showModal('', 'create');
                  }}
                  title='新增'
                />
              </div>
              <div style={{ marginTop: '13px' }}>{this.renderTable()}</div>
            </div>
            {visible && <ModalInst type={type} detailData={detailData} visible={visible} titleModal={title} setVisible={this.setVisible} getTableDataNew={this.getTableData} />}
          </div>
        }
      />
    );
  }
}
